import { defineStore } from 'pinia'
import request from '@/utils/request'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    roles: [],
    permissions: []
  }),

  getters: {
    isLogin: (state) => !!state.token,
    // 获取用户角色
    userRoles: (state) => state.roles,
    // 获取用户权限
    userPermissions: (state) => state.permissions
  },

  actions: {
    // 设置 Token
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    // 设置用户信息
    setUserInfo(info) {
      this.userInfo = info
      localStorage.setItem('userInfo', JSON.stringify(info))
    },

    // 设置用户角色
    setRoles(roles) {
      this.roles = roles
    },

    // 设置用户权限
    setPermissions(permissions) {
      this.permissions = permissions
    },

    // 登录
    async login(userInfo) {
      try {
        const { username, password } = userInfo
        const res = await request.post('/login', {
          username: username.trim(),
          password: password
        })
        
        if (res.data.token) {
          this.setToken(res.data.token)
          await this.getUserInfo() // 登录后获取用户信息
        }
        
        return res
      } catch (error) {
        console.error('登录失败：', error)
        throw error
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const res = await request.get('/info')
        const { user, roles, permissions } = res.data

        this.setUserInfo(user)
        this.setRoles(roles || [])
        this.setPermissions(permissions || [])
        
        return res.data
      } catch (error) {
        console.error('获取用户信息失败：', error)
        throw error
      }
    },

    // 登出
    async logout() {
      try {
        if (this.token) {
          await request.post('/logout')
        }
      } catch (error) {
        console.error('登出请求失败：', error)
      } finally {
        this.resetState()
      }
    },

    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = {}
      this.roles = []
      this.permissions = []
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },

    // 检查权限
    hasPermission(permission) {
      return this.permissions.includes(permission)
    },

    // 检查角色
    hasRole(role) {
      return this.roles.includes(role)
    }
  }
}) 